package com.zhonglz.util.redis;

import java.util.Collection;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

/****
 * redis
 * @author xiaozhong
 */
@Component
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
public class RedisUtils {
	
	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;

	// 默认过期时长(单位:秒)
	public static final long DEFAULT_EXPIRE = 60 * 60 * 24;

	// 不设置过期时长
	public static final long NOT_EXPIRE = -1;

	// 重命名Key，如果newKey已经存在，则newKey的原值被覆盖
	public void renameKey(String oldKey, String newKey) {
		redisTemplate.rename(oldKey, newKey);
	}

	// 重命名Key，如果newKey不存在时才重命名
	public boolean renameKeyNotExist(String oldKey, String newKey) {
		return redisTemplate.renameIfAbsent(oldKey, newKey);
	}

	// 删除指定的key
	public void deleteKey(String key) {
		redisTemplate.delete(key);
	}

	// 删除指定多个key
	public void deleteKey(String... keys) {
		Set<String> kSet = Stream.of(keys)//
				.collect(Collectors.toSet());
		redisTemplate.delete(kSet);
	}
	
	// 通过集合删除key
	public void deleteKey(Collection<String> keys) {
		Set<String> kSet = keys.stream()//
				.collect(Collectors.toSet());
		redisTemplate.delete(kSet);
	}

	// 设置key的过期时间
	public void expireKey(String key, long time, TimeUnit timeUnit) {
		redisTemplate.expire(key, time, timeUnit);
	}

	// 设置key在指定的日期过期
	public void expireKeyAt(String key, Date date) {
		redisTemplate.expireAt(key, date);
	}

	// 查询key的过期时间
	public long getKeyExpire(String key, TimeUnit timeUnit) {
		return redisTemplate.getExpire(key, timeUnit);
	}

	// 将key设置为永久有效
	public void persistKey(String key) {
		redisTemplate.persist(key);
	}

}
